<?php
namespace App\Admin\Controllers\Operation;

use App\Admin\Ajax\Operation\TCTotalAjax;
use App\Models\Basics\SysICountry;
use App\Models\Operation\TCTotalFile;
use App\Models\Product\ProductClassify;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Request;
class TotalCheckController extends AdminController{

    protected $title = '运营总表核验';

    protected $filters = [
        'start_date' => null,
        'end_date' => null,
        'country_id' => null,
        'classify_id' => null,
    ];

    protected function grid()
    {
        $filtersField = array_keys($this->filters);
        $filters = $this->_getFilters($filtersField);
        $this->_initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->_paginator($query);
        $action = getAction($filtersField);
        $filtersBlade = [];
        $filtersBlade['start_date'] = $this->filters['start_date'];
        $filtersBlade['end_date'] = $this->filters['end_date'];
        $filtersBlade['country_id'] = getOptions(SysICountry::options(),$this->filters['country_id']);
        $filtersBlade['classify_id'] = getOptions(ProductClassify::options(),$this->filters['classify_id']);
        return view('operation.total-check.index', compact('paginator','filtersBlade','action'));
    }

    private function _getFilters($filtersField){
        $startDate = request('start_date');
        $endDate = request('end_date');
        $reportDate = $this->__reportDate($startDate,$endDate);
        $filters = [];
        foreach ($filtersField as $field){
            if(array_key_exists($field,$reportDate)){
                $filters[$field] = $reportDate[$field];
            }else{
                $filters[$field] = request($field);
            }
        }
        return $filters;
    }

    private function _initFilters($filters){
        foreach ($filters as $field => $filter){
            $this->filters[$field] = $filter;
        }
    }

    private function __reportDate($start,$end){
        if(is_null($start) && is_null($end)){
            $startDate = date('Y-m-01');
            $endDate = date('Y-m-d');
        }elseif(!is_null($start) && is_null($end)){
            $startDate = $start;
            $endDate = strtotime($start) > time() ? date('Y-m-d') : date('Y-m-t',strtotime($start));
        }elseif(is_null($start) && !is_null($end)){
            $startDate = date('Y-m-01',strtotime($end));
            $endDate = $end;
        }else{
            $startDate = $start;
            $endDate = $end;
        }
        return ['start_date' => $startDate,'end_date' => $endDate];
    }

    private function _initQuery($filters){
        $query = TCTotalFile::query();
        foreach ($filters as $field => $filter){
            if(!$filter)continue;
            if($field == 'start_date'){
                $query->where('start_date','>=',$filter);
            }
            if($field == 'end_date'){
                $query->where('end_date','<=',$filter);
            }
            if(in_array($field,['country_id','classify_id'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    private function _paginator($query){
        return $query->orderBy('id', 'DESC')->paginate((int) (request("per_page",10)))->appends(Request::input());
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new TCTotalAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    protected function download($id){
        $re = TCTotalFile::query()->findOrFail($id);
        if(!$re) {
            admin_toastr('无文件记录！','error');
            return back();
        }
        try{
            $file = TCTotalFile::getFile($re->start_date,$re->end_date,$re->country_id,$re->classify_id);
            if(!file_exists($file)){
                admin_toastr('无文件！','error');
                return back();
            }
            return response()->download($file);
        }catch (\Exception $e){
            report($e);
            admin_toastr('操作失败！','error');
            return back();
        }
    }
}
